package com.bstek.urule.console.servlet.knowledge;

import com.bstek.urule.RuleException;
import com.bstek.urule.Utils;
import com.bstek.urule.console.servlet.base.BaseController;
import com.bstek.urule.runtime.KnowledgePackage;
import com.bstek.urule.runtime.KnowledgePackageWrapper;
import com.bstek.urule.runtime.cache.CacheUtils;
import com.bstek.urule.runtime.service.KnowledgePackageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchaoliang
 * @since 2021/12/9
 */
@Controller
public class LoadKnowledgeController extends BaseController {
    @Autowired
    private KnowledgePackageService knowledgePackageService;

    @PostMapping("/urule/loadknowledge")
    public KnowledgePackageWrapper konwledge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String packageId = req.getParameter("packageId");
        if (StringUtils.isEmpty(packageId)) {
            throw new RuleException("packageId can not be null");
        }
        packageId = Utils.decodeURL(packageId);
        String timestamp = req.getParameter("timestamp");
        KnowledgePackage knowledgePackage = CacheUtils.getKnowledgeCache().getKnowledge(packageId);
        if (knowledgePackage == null) {
            knowledgePackage = knowledgePackageService.buildKnowledgePackage(packageId);
            CacheUtils.getKnowledgeCache().putKnowledge(packageId, knowledgePackage);
        }
        if (StringUtils.isNotEmpty(timestamp)) {
            long remoteTimestamp = Long.valueOf(timestamp);
            long localTimestamp = knowledgePackage.getTimestamp();
            if (localTimestamp > remoteTimestamp) {
               return new KnowledgePackageWrapper(knowledgePackage);
            }
            throw new RuleException("时间不一致");
        } else {
            return new KnowledgePackageWrapper(knowledgePackage);
        }
    }

}
